package logic

import (
	"context"
	"errors"
	"guar/guarrpc/guarrpc"
	"guar/guarrpc/internal/svc"
	"guar/model/cache"
	"guar/model/mysql"
	"guar/pkg"

	"github.com/zeromicro/go-zero/core/logx"
)

type LoginLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewLoginLogic(ctx context.Context, svcCtx *svc.ServiceContext) *LoginLogic {
	return &LoginLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *LoginLogic) Login(in *guarrpc.LoginRequest) (*guarrpc.LoginResponse, error) {
	// todo: add your logic here and delete this line

	var users mysql.User
	result, _ := cache.Rdb.Get(l.ctx, "captcha"+in.Password).Result()
	if result != in.Captcha {
		return nil, errors.New("验证码错误，请重新输入")
	}

	mysql.DB.Debug().Where("username = ?", in.Username).Find(&users)
	if users.ID == 0 {
		user := mysql.User{
			Username: in.Username,
			Password: pkg.MD5(in.Password),
		}
		mysql.DB.Debug().Create(&user)
	}

	if pkg.MD5(in.Password) != users.Password {
		return nil, errors.New("密码错误，请重新输入")
	}

	return &guarrpc.LoginResponse{
		UserId: int64(users.ID),
	}, nil
}
